package boot.spring.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import boot.spring.entity.Permission;
import boot.spring.entity.Role;
import boot.spring.entity.Users;
import boot.spring.service.UserInfoService;
import boot.spring.util.MD5Utils;

public class CustomRealm extends AuthorizingRealm {

	@Autowired
	private UserInfoService userInfoService;

	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo
		(PrincipalCollection principals) {
		System.out.println("权限认证222222222-------------------------");
		//获取操作主体
		Users user= (Users) principals.getPrimaryPrincipal();
//		// 获取登录的用户名
//		String userName = (String) principals.getPrimaryPrincipal();
//		// 根据用户名查询是否有这个用户
//		UserInfo user = userInfoService.getUserByName(userName);
		// 把用户的角色和权限添加到shiro中
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 获取用户的角色
		for (Role r : user.getrList()) {
			// 把角色添加到shiro
			authorizationInfo.addRole(r.getRolekey());
			System.err.println("角色："+r.getRolekey());
			// 获取角色的权限
			for (Permission p : r.getpList()) {
				// 把权限添加到shiro
				System.err.println("权限："+p.getPidentifier());
				authorizationInfo.addStringPermission(p.getPidentifier());
			}
		}
		return authorizationInfo;
	}

	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo
		(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		System.out.println("登录认证-------------------------");
		
		UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) authenticationToken;
		//获取前台输入的登录名和密码
		String login_name = usernamePasswordToken.getUsername();
		String login_password = String.valueOf(usernamePasswordToken.getPassword());
		//根据用户名查询是否有这个用户
		System.out.println("----a------"+login_name);
		System.out.println("根据用户名查询是否有这个用户");
		Users user = userInfoService.getUserByName(login_name);
		System.out.println("----a------"+login_name);
		//获取MD5密码
		/*String generate = MD5Utils.generate(login_password);
		System.out.println("MD5:"+generate);*/
		if(user == null) {
			return null;
		}else {
			//验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, login_password, getName());
            return simpleAuthenticationInfo;
		}
	}
}
